package com.huike.report.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.huike.common.exception.BaseException;
import com.huike.contract.domain.ChannelStatistics;
import com.huike.report.domain.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huike.clues.domain.TbActivity;
import com.huike.clues.domain.TbAssignRecord;
import com.huike.clues.domain.TbClue;
import com.huike.clues.domain.vo.IndexStatisticsVo;
import com.huike.clues.mapper.SysDeptMapper;
import com.huike.clues.mapper.SysDictDataMapper;
import com.huike.clues.mapper.TbActivityMapper;
import com.huike.clues.mapper.TbAssignRecordMapper;
import com.huike.clues.mapper.TbClueMapper;
import com.huike.common.utils.SecurityUtils;
import com.huike.contract.domain.TbContract;
import com.huike.contract.mapper.TbContractMapper;
import com.huike.report.mapper.ReportMapper;
import com.huike.report.service.IReportService;

@Service
public class ReportServiceImpl implements IReportService {

    @Autowired
    private TbContractMapper contractMapper;


    @Autowired
    private SysDictDataMapper sysDictDataMapper;


    @Autowired
    private TbClueMapper clueMapper;

    @Autowired
    private TbActivityMapper activityMapper;


    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private TbAssignRecordMapper assignRecordMapper;
    
    @Autowired
    private ReportMapper reportMpper;



    @Override
    public List<TbContract> contractReportList(TbContract tbContract) {
       return contractMapper.selectTbContractList(tbContract);
    }








    @Override
    public List<TbClue> cluesStatisticsList(TbClue clue) {
        return clueMapper.selectTbClueForReport(clue);
    }

    @Override
    public List<ActivityStatisticsVo> activityStatisticsList(TbActivity query) {
        query.setStatus("2");
        List<TbActivity> activities= activityMapper.selectTbActivityList(query);
        Map<String, Object> timeMap = query.getParams();
        List<ActivityStatisticsVo> list=new ArrayList<>();
        for (TbActivity activity : activities) {
            ActivityStatisticsVo dto = new ActivityStatisticsVo();
            BeanUtils.copyProperties(activity, dto);
            TbClue tbClue = new TbClue();
            tbClue.setActivityId(activity.getId());
            tbClue.setChannel(activity.getChannel());
            tbClue.setParams(timeMap);
            Map<String, Object> clueCount = clueMapper.countByActivity(tbClue);
            if (clueCount != null) {
                dto.setCluesNum(Integer.parseInt(clueCount.get("total").toString()));
                if(clueCount.get("falseClues")!=null){
                    dto.setFalseCluesNum(Integer.parseInt(clueCount.get("falseClues").toString()));
                }
                if (clueCount.get("toBusiness") != null) {
                    dto.setBusinessNum(Integer.parseInt(clueCount.get("toBusiness").toString()));
                }
            }
            TbContract tbContract = new TbContract();
            tbContract.setChannel(activity.getChannel());
            tbContract.setActivityId(activity.getId());
            tbContract.setParams(timeMap);
            Map<String, Object> contractCount = contractMapper.countByActivity(tbContract);
            if (contractCount != null) {
                dto.setCustomersNum(Integer.parseInt(contractCount.get("customersNum").toString()));
                if(contractCount.get("amount")==null) {
                	dto.setAmount(0d);
                }else {
                	dto.setAmount((Double) contractCount.get("amount"));
                }
                if(contractCount.get("cost")==null) {
                	dto.setCost(0d);
                }else {
                	dto.setCost((Double) contractCount.get("cost"));
                }
                
            }
            list.add(dto);
        }
        return list;
    }


    @Override
    public IndexVo getIndex(IndexStatisticsVo request) {
        Long deptId= request.getDeptId();
        TbAssignRecord tbAssignRecord=new TbAssignRecord();
        tbAssignRecord.setLatest("1");
        assignRecordMapper.selectAssignRecordList(tbAssignRecord);
        return null;
    }


    /**
     * 获取首页基本数据
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public IndexBaseInfoVO getBaseInfo(String beginCreateTime, String endCreateTime) {
        //1 构建一个空的结果集对象
        IndexBaseInfoVO result = new IndexBaseInfoVO();
        //2 封装结果集属性
        // 2.1 由于查询需要用到用户名 调用工具类获取用户名
        String username = SecurityUtils.getUsername();
        // 2.2 开始查询第一个属性 线索数量
        result.setCluesNum(reportMpper.getCluesNum(beginCreateTime, endCreateTime, username));
        // 2.3 开始查询第一个属性 商机数量
        result.setBusinessNum(reportMpper.getBusinessNum(beginCreateTime, endCreateTime, username));
        // 2.4 开始查询第一个属性 合同数量
        result.setContractNum(reportMpper.getContractNum(beginCreateTime, endCreateTime, username));
        // 2.5 开始查询第一个属性 销售金额数量
        result.setSalesAmount(reportMpper.getSalesAmount(beginCreateTime, endCreateTime, username));
        //5 返回结果集对象
        return result;
    }

    @Override
    public IndexTodoInfoVo getTodoInfo(String beginCreateTime, String endCreateTime) {
        //1 构建一个空的结果集对象
        IndexTodoInfoVo result = new IndexTodoInfoVo();
        //2 封装结果集属性
        // 2.1 由于查询需要用到用户名 调用工具类获取用户名
        String username = SecurityUtils.getUsername();

        result.setTofollowedCluesNum(reportMpper.getTofollowedCluesNum(beginCreateTime, endCreateTime, username)); ;

        result.setTofollowedBusinessNum (reportMpper.getTofollowedBusinessNum(beginCreateTime, endCreateTime, username));

        result.setToallocatedCluesNum (reportMpper.getToallocatedCluesNum(beginCreateTime, endCreateTime, username));

        result.setToallocatedBusinessNum(reportMpper.getToallocatedBusinessNum(beginCreateTime, endCreateTime, username));

        return result;
    }

    @Override
    public IndexTodayInfoVo getTodayInfo() {

        IndexTodayInfoVo result = new IndexTodayInfoVo();
        String username = SecurityUtils.getUsername();
        result.setTodayCluesNum(reportMpper.getTodayCluesNum(username));
        result.setTodayContractNum(reportMpper.getTodayContractNum(username));
        result.setTodayBusinessNum(reportMpper.getTodayBusinessNum(username));
        result.setTodaySalesAmount(reportMpper.getTodaySalesAmount(username));
        return result;
    }

    @Override
//    public List<Map<String,Object>> subjectStatistics(String beginCreateTime, String endCreateTime) {
    public List<SubjectStatisticsVo> subjectStatistics(String beginCreateTime, String endCreateTime) {
        return reportMpper.getsubjectStatistics(beginCreateTime,endCreateTime);
    }

    @Override
    public CluesStatisticsVo cluesStatistics(String beginCreateTime, String endCreateTime) {
        CluesStatisticsVo cluesStatisticsVo = new CluesStatisticsVo();
        List<String> xAxis = new ArrayList<>();//beginCreateTime-->endCreateTime
        List<CluesNumVo> series = new ArrayList();

        CluesNumVo cluesNumVo1 = new CluesNumVo();
        cluesNumVo1.setName("新增线索数量");
        List<Integer> data1 = new ArrayList<>();
        CluesNumVo cluesNumVo2 = new CluesNumVo();
        cluesNumVo2.setName("线索总数量");
        List<Integer> data2 = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date beginDate = null;
        Date endDate = null;
        try {
            beginDate = sdf.parse(beginCreateTime);
            endDate = sdf.parse(endCreateTime);
        } catch (ParseException e) {
            throw new BaseException(e.getMessage());
        }

        Calendar calendar1 = new GregorianCalendar();
        Calendar calendar2 = new GregorianCalendar();
        calendar1.setTime(beginDate);
        calendar2.setTime(endDate);
        int begin = calendar1.get(Calendar.DAY_OF_YEAR);
        int end = calendar2.get(Calendar.DAY_OF_YEAR);

        for (int i = 0; i <= (end - begin); i++) {
            Integer today = clueMapper.selectTodayCluesCount(sdf.format(calendar1.getTime()));
            Integer count = clueMapper.selectCluesCount(sdf.format(calendar1.getTime()));
            xAxis.add(sdf.format(calendar1.getTime()));
            data1.add(today);
            data2.add(count);
            calendar1.add(Calendar.DAY_OF_YEAR,1);
        }
        cluesNumVo1.setData(data1);
        cluesNumVo2.setData(data2);
        series.add(cluesNumVo1);
        series.add(cluesNumVo2);
        cluesStatisticsVo.setXAxis(xAxis);
        cluesStatisticsVo.setSeries(series);
        return cluesStatisticsVo;
    }

    /**
     * 渠道查询
     * @param beginCreateTime
     * @param endCreateTime
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<ChannelStatistics> getChannelStatisticsList(String beginCreateTime, String endCreateTime, Integer pageNum, Integer pageSize) {
        Integer index=(pageNum-1)*pageSize;
        return contractMapper.selectChannelStatisticsList(beginCreateTime,endCreateTime,index,pageSize);
    }

    @Override
    public Long getTotal(String beginCreateTime, String endCreateTime) {

        return contractMapper.getTotal(beginCreateTime,endCreateTime);
    }

    @Override
    public List<ReportVo> getDeptStatisticsList(String beginCreateTime, String endCreateTime,
                                                Integer pageNum, Integer pageSize) {
        Integer pageStart = (pageNum - 1) * pageSize;
        Integer pageEnd = pageSize;
        return reportMpper.getDeptStatisticsList(beginCreateTime, endCreateTime, pageStart, pageEnd);
    }

    @Override
    public Integer getDeptTotal(String beginCreateTime, String endCreateTime) {
        return reportMpper.getTotal(beginCreateTime, endCreateTime);
    }
}